package leetcode_701_800;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class LeeCode_735 {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(asteroidCollision(new int[]{5, 10, -5})));
        System.out.println(Arrays.toString(asteroidCollision(new int[]{8, -8})));
        System.out.println(Arrays.toString(asteroidCollision(new int[]{10, 2, -5})));
        System.out.println(Arrays.toString(asteroidCollision(new int[]{-2, -1, 1, 2})));
    }

    private static int[] asteroidCollision(int[] asteroids) {
        Deque<Integer> queue = new ArrayDeque<>();
        for (int pl : asteroids) {
            if (queue.isEmpty()) {
                queue.add(pl);
                continue;
            }
            int tl = pl;
            boolean flag = true;
            while (!queue.isEmpty() && queue.peek() > 0 && tl < 0) {
                if (Math.abs(tl) == Math.abs(queue.peek())) {
                    queue.pop();
                    flag = false;
                    break;
                } else if (Math.abs(tl) > Math.abs(queue.peek())) {
                    queue.pop();
                } else {
                    tl = queue.pop();
                }
            }
            if (flag)
                queue.push(tl);
        }
        int[] ans = new int[queue.size()];
        for (int i = ans.length - 1; i >= 0; i--) {
            ans[i] = queue.pop();
        }
        return ans;
    }
}